package edu.faytechcc.csc251.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author kent
 */
public class MTGDBQuery {

    private final String DB_URL = "jdbc:derby:MTGCardDB";
    private Connection conn;
    //private String[][] data;
    private String[] colNames;
    private ArrayList<String[]> dataArrayList;

    /**
     * Constructor
     * @param query
     */
    public MTGDBQuery(String query){
        getDatabaseConnection();

        try {
            try (Statement stmt = conn.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY)) {
                ResultSet resultSet = stmt.executeQuery(query);
                
                resultSet.last();
                int numRows = resultSet.getRow();
                resultSet.first();
                
                ResultSetMetaData meta = resultSet.getMetaData();
                
                colNames = new String[meta.getColumnCount()];
                for (int i = 0; i < meta.getColumnCount(); i++) {
                    colNames[i] = meta.getColumnLabel(i + 1);
                }

//                data = new String[numRows][meta.getColumnCount()];
//                for (int row = 0; row < numRows; row++) {
//                    for (int col = 0; col < meta.getColumnCount(); col++) {
//                        data[row][col] = resultSet.getString(col + 1);
//                    }
//                    resultSet.next();
//                }
                dataArrayList = new ArrayList<String[]>();
                for (int row = 0; row < numRows; row++)
                {
                    String[] rowData = new String[meta.getColumnCount()];
                    for (int col = 0; col < meta.getColumnCount(); col++)
                    {
                        rowData[col] = resultSet.getString(col+1);
                    }
                    dataArrayList.add(rowData);
                    resultSet.next();
                }
            }
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(MTGDBQuery.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
    }

    private void getDatabaseConnection() {
        try {
            conn = DriverManager.getConnection(DB_URL);
        } catch (SQLException ex) {
            ex.printStackTrace();
            System.exit(0);
        }
    }

    public String[] getColumnNames() {
        return colNames;
    }

//    public String[][] getData() {
//        return this.data;
//    }
    
    public ArrayList getList()
    {
        return dataArrayList;
    }
}
